package com.chenyun.message.tio;

import cn.hutool.core.util.StrUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.tio.core.ChannelContext;
import org.tio.core.Tio;
import org.tio.http.common.HttpRequest;
import org.tio.http.common.HttpResponse;
import org.tio.http.common.HttpResponseStatus;
import org.tio.websocket.common.WsRequest;
import org.tio.websocket.common.WsResponse;
import org.tio.websocket.common.WsSessionContext;
import org.tio.websocket.server.handler.IWsMsgHandler;

import java.io.Serializable;
import java.util.Objects;

/**
 * WsMsgHandler：
 * Description:
 *
 * @author: Lonni
 * @date: 2024/5/7 0007 15:02
 */
public class WsMsgHandler implements IWsMsgHandler {

    private static Logger log = LoggerFactory.getLogger(WsMsgHandler.class);

    public static WsMsgHandler me = new WsMsgHandler();

    /**
     *  握手时走这个方法，业务可以在这里获取cookie，request参数等
     * @param httpRequest
     * @param httpResponse
     * @param channelContext
     * @return
     * @throws Exception
     */
    @Override
    public HttpResponse handshake(HttpRequest httpRequest, HttpResponse httpResponse, ChannelContext channelContext) throws Exception {
        log.info("handshake....");
        String userId = httpRequest.getParam("uid");
        if (StrUtil.isBlank(userId)) {
            log.info("未检测到uid参数.....");
            httpResponse.setStatus(HttpResponseStatus.C401);
        }
        return httpResponse;
    }

    @Override
    public void onAfterHandshaked(HttpRequest httpRequest, HttpResponse httpResponse, ChannelContext channelContext) throws Exception {

        log.info("onAfterHandshaked....握手成功");
        //TODO 绑定到所有组
        Tio.bindGroup(channelContext, "");
        //绑定会话
        String userId = httpRequest.getParam("uid");
        Tio.bindUser(channelContext,userId);
        WsResponse wsResponse = WsResponse.fromText("如果您看到此消息，表示您已成功连接 WebSocket 服务器", "UTF-8");
        Tio.send(channelContext,wsResponse);

    }

    /**
     *  字节消息（binaryType = arraybuffer）过来后会走这个方法
     * @param wsRequest
     * @param bytes
     * @param channelContext
     * @return
     * @throws Exception
     */
    @Override
    public Object onBytes(WsRequest wsRequest, byte[] bytes, ChannelContext channelContext) throws Exception {
        log.info("onBytes....");
        return null;
    }

    @Override
    public Object onClose(WsRequest wsRequest, byte[] bytes, ChannelContext channelContext) throws Exception {
        log.info("onClose....");
        //解绑组
        Tio.unbindGroup(channelContext);
        //解绑用户
        Tio.unbindUser(channelContext);
        Tio.remove(channelContext, "receive close flag");
        return null;
    }

    /**
     * text 消息
     * @param wsRequest
     * @param s
     * @param channelContext
     * @return
     * @throws Exception
     */
    @Override
    public Object onText(WsRequest wsRequest, String text, ChannelContext channelContext) throws Exception {
        log.info("接收到消息:{}",text);
        WsSessionContext wsSessionContext = (WsSessionContext) channelContext.get();
        //获取websocket握手包
        HttpRequest httpRequest = wsSessionContext.getHandshakeRequest();
        if (log.isDebugEnabled()) {
            log.debug("握手包:{}", httpRequest);
        }

//		log.info("收到ws消息:{}", text);

        if (Objects.equals("心跳内容", text)) {
            return null;
        }
        //channelContext.getToken()
        //String msg = channelContext.getClientNode().toString() + " 说：" + text;
        String msg = "{name:'" + channelContext.userid + "',message:'" + text + "'}";
        //用tio-websocket，服务器发送到客户端的Packet都是WsResponse
        WsResponse wsResponse = WsResponse.fromText(msg, "utf-8");
        //群发
        Tio.sendToGroup(channelContext.tioConfig, "1111", wsResponse);

        //返回值是要发送给客户端的内容，一般都是返回null
        return null;
    }
}



